<?php

declare(strict_types=1);

namespace App\Service;

use App\Constants\ErrorCode;
use App\Library\Common;
use App\Model\AppUser;
use App\Model\FlyShop;
use App\Model\FlyTalkLog;
use App\Model\FlyTalkRoom;
use App\Model\FlyTalkRoomUser;
use Hyperf\DbConnection\Db;
use PhpParser\Node\Expr\New_;
use Swoole\Curl\Exception;

class TalkRoomService extends BaseService
{

    /**
     * 获取房间,创建或查询
     * @param int $shop_id
     * @param int $user_id
     * @return object
     */
    public function get_room(int $shop_id,int $user_id): object
    {
        $FlyTalkRoomUser =  New  FlyTalkRoomUser();
        $FlyTalkRoom =  New  FlyTalkRoom();
        $room_info =  $FlyTalkRoom->where([
            'shop_id'=>$shop_id,
            'user_id'=>$user_id
        ])->with('talk_log')->first();
        if(!$room_info){
            Db::beginTransaction();
            try {
                $room_id =  $FlyTalkRoom->insertGetId([
                    'shop_id'=>$shop_id,
                    'user_id'=>$user_id,
                    'created_at'=>date('Y-m-d H:i:s'),
                    'room_type'=>1,
                ]);
                $arr[] = [
                    'room_id'=>$room_id,
                    'link_id'=>$shop_id,
                    'type'=>1,
                ];
                $arr[] = [
                    'room_id'=>$room_id,
                    'link_id'=>$user_id,
                    'type'=>2,
                ];
                $FlyTalkRoomUser->insert($arr);
                Db::commit();
                $room_info = $FlyTalkRoom->where([
                    'shop_id'=>$shop_id,
                    'user_id'=>$user_id
                ])->with('talk_log')
                    ->first();
            }catch (Exception $exception){
                Db::rollBack();
                throw new \RuntimeException($exception->getMessage(), ErrorCode::SERVER_ERROR);
            }
        }
        return $room_info;
    }


//    todo 1商户的，2用户的
    public function room_list(int $link_id=0,int $type=1)
    {
        $where = [];
        if($type==1){
            $where['shop_id'] = $link_id;
        }else{
            $where['user_id'] = $link_id;
        }
        return FlyTalkRoom::query()
            ->with('shop_info')
            ->with('user_info')
            ->with('talk_log')
            ->where($where);
    }

    //type1商户的，2用户的
    //  is_read是否已读，是否需要时间
    public function count_size($admin_id,$room_id,$type=1,$is_read=''){
        $where = [];
        $where['room_id'] = $room_id;
        $FlyTalkLog = New FlyTalkLog();
        $RoomUser = New FlyTalkRoomUser();
        if($is_read==0){
            $room_user_info = $RoomUser->where(['link_id'=>$admin_id,'type'=>$type])->first();
            $where[] = ['send_time','>',$room_user_info->last_ack??0];
        }
        return $FlyTalkLog
            ->where($where)
            ->count('id');
    }


    public function add_log(array $data)
    {
       return $this->redis_push('Talk_log',$data,'right');
    }
    public function create_log(array $data)
    {
        Db::beginTransaction();
        try {
            FlyTalkRoomUser::query()->where(['room_id'=>$data['room_id'],'link_id'=>$data['send_by'],'type'=>$data['type']])->update(['last_ack'=>time()]);
            if(isset($data['link_id'])){
                unset($data['link_id']);
            }
            if(isset($data['af_user_id'])){
                unset($data['af_user_id']);
            }
            $data['created_at'] = Common::date_time(2);
            FlyTalkLog::query()->insertGetId(Common::filter_null($data));
            Db::commit();
        }catch (Exception $exception){
            Db::rollBack();
            throw new \RuntimeException($exception->getMessage(), ErrorCode::SERVER_ERROR);
        }
    }
    public function get_log()
    {
        return $this->redis_pop('Talk_log');
    }
    public function get_room_log(int $room_id)
    {
        return  FlyTalkLog::query()->where('room_id',$room_id)->orderBy('id','desc');
    }

    public function update_ack(int $room_id, int $user_id,int $type)
    {
       return FlyTalkRoomUser::query()->where(['room_id'=>$room_id,'link_id'=>$user_id,'type'=>$type])->update(['last_ack'=>time()]);
    }

    public function check_user(int $room_id, int $link_id,int $type)
    {
        return FlyTalkRoomUser::query()->where(['room_id'=>$room_id,'link_id'=>$link_id,'type'=>$type])->exists();
    }

    public function room_user(int $room_id)
    {
        $key = 'ws_room_'.$room_id;
        $room_user_list =  $this->redis_get($key);
        if($room_user_list){
               return $room_user_list;
        }else{
            $room_user_list = FlyTalkRoomUser::query()
                ->where(['room_id'=>$room_id])
                ->select()->get()->toArray();
            $this->redis_set($key,$room_user_list);
            return $room_user_list;
        }
    }
    public function room_user_last_ack(int $room_id)
    {
        $key = 'room_user_last_ack'.$room_id;
        $room_user_list =  $this->redis_get($key);
        if($room_user_list){
            return $room_user_list;
        }else{
            $room_user_list = FlyTalkRoomUser::query()
                ->where(['room_id'=>$room_id])
                ->select()->get()->toArray();
            $this->redis_set($key,$room_user_list,3);
            return $room_user_list;
        }
    }
}